<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisibleShow()">添加分类</el-button>
        </el-col>
      </el-row>

      <zk-table
      class="treeTable"
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="true"
      >
        <template slot="isOk" slot-scope="scope">
            <i class="el-icon-success" style="color: lightgreen" v-if="scope.row.cat_deleted===false"></i>
            <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <template slot="sorts" slot-scope="scope">
            <el-tag type="success" v-if="scope.row.cat_level ===0">一级</el-tag>
            <el-tag type="info" v-else-if="scope.row.cat_level ===1">二级</el-tag>
            <el-tag type="warning" v-else-if="scope.row.cat_level ===2">三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
            <el-button type="success" icon="el-icon-edit" @click="editCateVisibleShow(scope.row)"  size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleCate(scope.row.cat_id)" size="mini">删除</el-button>
        </template>
      </zk-table>
      <el-pagination
        @size-change="handleChangeSize"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>


    <!-- 添加对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addDialogVisible"
      @closed="addDialogVisibleClosed('add')"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：" prop="">
            <el-cascader
                expand-trigger="hover"
                v-model="selected"
                :options="parentCateList"
                :props="cascaderProps"
                @change="parentCateChange"
                change-on-select
                clearable>
            </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisibleClosed('add')">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </div>
    </el-dialog>

     <!-- 修改对话框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editDialogVisible"
      @closed="addDialogVisibleClosed('edit')"
    >
      <el-form
        :model="editCateForm"
        :rules="addCateFormRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisibleClosed('edit')">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateId:'',
      cateList: [],
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      tatal: 0,
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          prop: "cat_deleted",
          type: "template",
          template: 'isOk'
        },
        {
          label: "排序",
          prop: "cat_level",
          type: "template",
          template: 'sorts'
        },
        {
          label: "操作",
          type: "template",
          template: 'opt'
        }
      ],
      addDialogVisible: false,
      editDialogVisible:false,
      addCateForm:{
          cat_name:'',
          cat_pid: 0,
          cat_level:0
      },
      editCateForm:{
          cat_name:''
      },
      addCateFormRules:{
          cat_name:[
              {
                required : true,
                message: '请输入分类名称',
                trigger:'blur'
              }
          ]
      },
      parentCateList:[],
      selected:[],
      cascaderProps: {
          value:'cat_id',
          label:'cat_name',
          children:'children'
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) return this.$message.error("获取列表失败")
      this.cateList = res.data.result
      this.total = res.data.total
      console.log(res)
    },
    handleChangeSize(res){
        this.queryInfo.pagesize=res
        this.getCateList()
    },
    handleCurrentChange(val){
        this.queryInfo.pagenum=val
        this.getCateList()
    },
    deleCate(id){
        this.$confirm('此操作将删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          showCancelButton: true,
          cancelButtonClass : 'cancel',
          type: 'warning'
        }).then(async () => {
          const {data : res} =await this.$http.delete(`categories/${id}`)
          console.log(res)
          if(res.meta.status!==200) return this.$message.error('删除失败')
          this.getCateList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    addDialogVisibleClosed(type){
        if(type==='add'){
            this.$refs.addCateFormRef.resetFields()
            this.selected=[]
            this.addDialogVisible=false
        }else{
            this.$refs.editCateFormRef.resetFields()
            this.selected=[]
            this.editDialogVisible=false
        }
    },
    async addDialogVisibleShow(){
            const {data:res} =await this.$http.get("categories", {
                params: {type: 2},
            })
            if (res.meta.status !== 200) return this.$message.error("获取列表失败")
            this.parentCateList=res.data
            this.addDialogVisible=true
    },
    parentCateChange(){
        if(this.selected.length>0){
            this.addCateForm.cat_pid=this.selected[this.selected.length-1]   
        }
        this.addCateForm.cat_level=this.selected.length
        
    },
    addCate(){
        this.$refs.addCateFormRef.validate(async value =>{
            if(!value) return
            const {data:res} =await this.$http.post('categories',this.addCateForm)
            console.log(res);
            if(res.meta.status!==201) return this.$message.error('添加失败')
            this.addDialogVisible=false
            this.getCateList()
            return this.$message.success(res.meta.msg)
        })
    },
    editCateVisibleShow(row){ 
        this.editCateForm.cat_name=row.cat_name
        this.cateId=row.cat_id
        this.editDialogVisible=true
    },
    editCate(){
        this.$refs.editCateFormRef.validate(async value =>{
            if(!value) return
            const {data:res} =await this.$http.put(`categories/${this.cateId}`,this.editCateForm)
            if(res.meta.status!==200) return this.$message.error('更新失败')
            this.editDialogVisible=false
            this.getCateList()
            return this.$message.success(res.meta.msg)
        })
    }

  },
};
</script>

<style lang="less" scoped>
    .treeTable{
        margin-top: 15px;
    }
    .el-cascader{
        width:100%;
    }
</style>
